<?php /** @noinspection PhpUndefinedMethodInspection */

namespace App\Http\Controllers\API;

use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function __construct(Request $request)
    {
        $this->middleware('auth:api', ['except' => ['login', 'register','refresh']]);
    }
    /**用户登录*/
    public function login(Request $request)
    {

        $input = $request->validate([
            'mobile'=> 'required|numeric|digits:11',
            'password'=>'required|string',
        ]);

        $token = Auth::attempt($input);

        if (!$token) {
            return Fail(__("login.no"));
        }
        $user = Auth::user();
        $lang = getLang();
        $userData = [
            'id'=>$user->id,
            'name'=>$user->{"name_{$lang}"}
        ];

        $data = [
            'user' => $userData,
            'token' => $token
        ];
        return Success(__('login.yes'),$data);
    }

    /**注册用户*/
    public function register(Request $request)
    {
        $input = $request->validate([
                                'mobile'=> 'required|numeric|digits:11',
                                'password'=>'required|string',
                            ]);
        $USER = User::query();
        if($USER->Where("mobile",$input['mobile'])->exists()){
            return Fail(__("login.register_user_exists"));
        }
        else{

            $input['password']  = Hash::make($input['password']);
            $user =$USER->create($input);

            return Success(__("login.register_yes"),$user->toArray());
        }

    }

    /**退出登录*/
    public function logout():JsonResponse
    {
        Auth::logout();
        return Success(__('login.logged_out'));
    }

    /**刷新token*/
    public function refresh(Request $request)
    {
        if(!Auth::check())return Fail('Token 已过期!');

        $user = Auth::user();
        $lang = getLang();
        $userData = [
            'id'=>$user->id,
            'name'=>$user->{"name_{$lang}"}
        ];

        $data = [
            'user' => $userData,
            'token' =>Auth::refresh()
        ];
        return Success(__('login.refresh_yes'),$data);
    }

    public function test(): JsonResponse
    {
        $user = Auth::user();
        return Success(null,['name'=>$user->{"name_".getLang()}]);
    }
}
